package com.weixing.mall.provider.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.core.enums.OrderAppTagEnum;
import com.weixing.mall.core.enums.OrderSysTagEnum;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.utils.CommonUtil;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.vo.MemberRpcVo;
import com.weixing.mall.provider.api.model.vo.SysUserEditVo;
import com.weixing.mall.provider.api.service.GoodsFeign;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.api.service.SysConfigServiceFeign;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.service.*;
import com.weixing.mall.provider.mapper.AfterSaleImgMapper;
import com.weixing.mall.provider.mapper.AfterSaleMapper;
import com.weixing.mall.provider.mapper.AfterSaleOperationMapper;
import com.weixing.mall.provider.mapper.OrderMapper;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.*;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.util.CommUtil;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author wx
 * @Date 2019/9/26 17:42
 * @Version 1.0
 */

/**
 * <p>
 * 订单模块-售后订单表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-20
 */
@Service
public class AfterSaleServiceImpl extends ServiceImpl<AfterSaleMapper, AfterSale> implements IAfterSaleService {


    @Autowired
    private AfterSaleMapper afterSaleMapper;
    @Autowired
    private AfterSaleImgMapper afterSaleImgMapper;
    @Autowired
    private AfterSaleOperationMapper afterSaleOperationMapper;
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private SysConfigServiceFeign sysConfigService;
    @Autowired
    private MemberServiceRpc memberServiceRpc;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private AgentServiceRpc agentServiceRpc;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderBindingService orderBindingService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAfterSaleOperationService afterSaleOperationService;
    @Autowired
    private AgentProfitFeign agentProfitFeign;
    @Autowired
    private IOrderLogService orderLogService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ActivityRpcService activityRpcService;
    @Autowired
    private IOrderGoodsService goodsService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(AfterSaleDto afterSaleDto, Long mid) {
        //客户调用会员接口查询
        MemberRpcVo memberRpcVo = null;
        Result<MemberRpcVo> result = memberServiceRpc.selectById(mid);
        if (result.isSuccess()) {
            memberRpcVo = result.getData();
        }
        AfterSale afterSale = new AfterSale();
        BeanUtils.copyProperties(afterSaleDto, afterSale);
        afterSale.setAfterSaleType(afterSaleDto.getAfterSaleType().getValue());
        afterSale.setMemberId(mid);
        //Solution 1 退款  2 换货
        if (afterSale.getAfterSaleType() == 1) {
            afterSale.setSolution(AfterSalesTypeEnum.RETURN_GOODS.getValue());
        } else {
            afterSale.setSolution(AfterSalesTypeEnum.EXCHANE_GOODS.getValue());
        }
//        //售后订单编号  TODO
//        afterSale.setAfterSaleSn();
        //新增就设置售后订单状态为初审中
        afterSale.setStatus(AfterSaleAuditEnum.WAIT_AUIT.getValue());
        afterSale.setReceiveTime(new Date());
        //新增售后
        afterSaleMapper.insert(afterSale);

        AfterSaleImg afterSaleImg = new AfterSaleImg();
        String[] imgs = afterSaleDto.getImgs();
        if (imgs != null) {
            for (int i = 0; i < imgs.length; i++) {
                afterSaleImg.setAfterSaleId(afterSale.getId());
                afterSaleImg.setImg(imgs[i]);
                afterSaleImgMapper.insert(afterSaleImg);
            }
        }

        //用户售后记录组织
        AfterSaleOperation afterSaleOperation = new AfterSaleOperation();

        //售后id
        afterSaleOperation.setAfterSaleId(afterSale.getId());
        //用户id
        afterSaleOperation.setOperatorId(mid);
        if (memberRpcVo != null) {
            //用户昵称
            afterSaleOperation.setOperator(memberRpcVo.getNickName());
        }
        //角色是客户
        afterSaleOperation.setOperatorType(0);
        //审核结果是0 代表 填成"用户退回"
        afterSaleOperation.setAuditResult(0);
        afterSaleOperation.setAuditRemark("用户退回");
        afterSaleOperation.setOperatorRemark("用户退回");
        afterSaleOperation.setCreatedTime(new Date());
        //售后记录
        afterSaleOperationMapper.insert(afterSaleOperation);

        //将售后订单状态设置为售后状态
        if (ObjectUtil.isNotEmpty(afterSaleDto) && afterSaleDto.getOrderId() != null) {
            orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId, afterSaleDto.getOrderId())
                    .set(Order::getOrderStatus, OrderStateEnum.AFTER_SALE.getValue())
                    .set(Order::getFrontOrderStatus, OrderFrontStateEnum.AFTER_SALE.getValue())
                    .set(Order::getAfterSaleTag,1));
            //更新订单标签状态
            if (afterSale.getAfterSaleType() == 1) {
                orderService.updateTag(afterSaleDto.getOrderId(), OrderSysTagEnum.THZ_TAG_501.getValue(), OrderAppTagEnum.THZ_TAG_501.getValue());
            } else {
                orderService.updateTag(afterSaleDto.getOrderId(), OrderSysTagEnum.THZ_HHG_507.getValue(), OrderAppTagEnum.THZ_HHG_507.getValue());
            }


        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public AfterSaleRefundVo selectRefundDetails(long id) {
        AfterSaleRefundVo afterSaleRefundVo = afterSaleMapper.selectRefundDetails(id);
        //将地址组合在一起
        afterSaleRefundVo.setAddress(afterSaleRefundVo.getProvince() + afterSaleRefundVo.getCity() + afterSaleRefundVo.getRegion() + afterSaleRefundVo.getAddrDetail());
        return afterSaleRefundVo;
    }

    @Override
    @Transactional(timeout = 10)
    public AfterSaleExchangeGoodsVo selectExchangeGoodsDetails(long id) {
        AfterSaleExchangeGoodsVo afterSaleExchangeGoodsVo = afterSaleMapper.selectExchangeGoodsDetails(id);
        return afterSaleExchangeGoodsVo;
    }

    @Override
    public IPage<AfterSaleVo> selectAfterSaleList(Page page, AfterSaleQuery afterSaleQuery) {
        //此方法废弃--转为order表内多级代理Id or查询
        Long[] agentIds = null;
        IPage<AfterSaleVo> pageList = afterSaleMapper.selectAfterSaleList(page, afterSaleQuery, agentIds);

        return pageList;
    }

    private Long[] agentIds(Long agentId) {
        Long[] agentIds = null;
        agentIds = agentServiceRpc.selectAgentTreeByParentId(agentId);
        if (agentIds != null) {
            List<Long> list = new ArrayList<>(Arrays.asList(agentIds));
            list.add(agentId);
            agentIds = list.toArray(new Long[list.size()]);
        } else {
            agentIds = new Long[]{agentId};
        }
        return agentIds;
    }

    @Override
    public List<AfterSaleVo> selectAfterSaleList(AfterSaleQuery afterSaleQuery) {
        return afterSaleMapper.selectAfterSaleList(afterSaleQuery, null);
    }

    @Override
    public void afterSaleChgType(AfterSaleChgTypeDto afterSaleChgTypeDto) {
        afterSaleMapper.afterSaleChgType(afterSaleChgTypeDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void afterSaleChgProblem(AfterSaleChgProblemDto ascpd, SysAuth auth) {
        //afterSaleMapper.afterSaleChgProblem(afterSaleChgProblemDto);
        Assert.notNull(ascpd.getId(), "参数null");
        update(new LambdaUpdateWrapper<AfterSale>().eq(AfterSale::getId, ascpd.getId())
                .set(AfterSale::getIsProblem, ascpd.getIsProblem().getValue())
                .set(AfterSale::getAfterSaleResult, AfterSaleResultEnum.PROBLEM_ORDER.getValue())
                .set(AfterSale::getIsHandle, AfterSaleIsHandleEnum.NO.getValue())
                .set(AfterSale::getStatus, AfterSaleAuditEnum.FINISHED.getValue())
                .set(AfterSale::getCheckTime, new Date()));
        //变更订单标签状态
        AfterSale getAfteSale = getById(ascpd.getId());
        if (ObjectUtil.isNotEmpty(getAfteSale)) {
            orderService.updateTag(getAfteSale.getOrderId(), OrderSysTagEnum.YTHC_TAG_505.getValue(), OrderAppTagEnum.YTHC_TAG_505.getValue());
            //判断是否是退货订单
            if (AfterSalesTypeEnum.RETURN_GOODS.getValue().equals(getAfteSale.getAfterSaleType())) {
                //回滚代理商返利
                Result result = agentProfitFeign.unProfit(getAfteSale.getOrderId());
                if (!result.isSuccess()) {
                    throw new BusinessException("调用回滚返利服务失败");
                }
              Order order=new Order();
                order.setId(getAfteSale.getOrderId());
                order.setUpdatedTime(new Date());
                orderService.updateById(order);
                //订单退货操作日志
                orderLogService.addOrderLog(getAfteSale.getOrderId(), OrderLogTypeEnum.REFUND.getValue(), auth.getUid(), auth.getRealName());
            }
        }
        //售后操作记录
        AfterSaleOperation afterSaleOperation = new AfterSaleOperation();
        //操作员id
        afterSaleOperation.setOperatorId(auth.getUid());
        //操作员姓名
        afterSaleOperation.setOperator(auth.getRealName());
        //售后订单
        afterSaleOperation.setAfterSaleId(ascpd.getId());
        //角色为接收员
        afterSaleOperation.setOperatorType(AfterSaleOperatorTypeEnum.TYPE2.getValue());
        afterSaleOperation.setAuditResult(AfterSaleResultEnum.PROBLEM_ORDER.getValue());
        //审核备注
        afterSaleOperation.setAuditRemark("入问题订单");
        //操作备注
        afterSaleOperation.setOperatorRemark("入问题订单");
        afterSaleOperation.setCreatedTime(DateUtil.date());
        afterSaleOperationMapper.insert(afterSaleOperation);
    }

    @Override
    public void afterSaleChgStatus(AfterSaleChgStatusDto ascsd) {
        AfterSale afterSale = new AfterSale();
        if (ObjectUtil.isNotEmpty(ascsd) && ascsd.getId() != null) {
            afterSale.setId(ascsd.getId());
            Integer sysTag = OrderSysTagEnum.YTHK_TAG_502.getValue();
            Integer appTag = OrderAppTagEnum.YTHK_TAG_502.getValue();
            //若客服拒绝则将售后订单状态改为已完成，售后结果改为驳回
            if (ascsd.getStatus() != null && AfterSaleAuditEnum.REFUSE_AUIT.getValue().equals(ascsd.getStatus().getValue())) {
                afterSale.setStatus(AfterSaleAuditEnum.FINISHED.getValue());
                afterSale.setAfterSaleResult(AfterSaleResultEnum.REJECT.getValue());
                afterSale.setAuditedTime(new DateTime());

                sysTag = OrderSysTagEnum.BH_TAG_506.getValue();
                appTag = OrderAppTagEnum.BH_TAG_506.getValue();
            } else {
                afterSale.setStatus(ascsd.getStatus().getValue());
                afterSale.setAuditedTime(new DateTime());
            }
            updateById(afterSale);
            //变更订单标签状态
            AfterSale getAfteSale = getById(ascsd.getId());
            if (ObjectUtil.isNotEmpty(getAfteSale)) {
                orderService.updateTag(getAfteSale.getOrderId(), sysTag, appTag);
            }
            //售后被拒绝订单售后中状态变更为已完成
            if (ascsd.getStatus() != null && AfterSaleAuditEnum.REFUSE_AUIT.getValue().equals(ascsd.getStatus().getValue()) && ObjectUtil.isNotEmpty(getAfteSale)) {
                orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId, getAfteSale.getOrderId()).set(Order::getOrderStatus, OrderStateEnum.FINISHED.getValue()));
            }
            Order order=new Order();
            order.setUpdatedTime(new Date());
            order.setId(getAfteSale.getOrderId());
            orderService.updateById(order);
        }
        // afterSaleMapper.afterSaleChgStatus(afterSaleChgStatusDto);
    }

    @Override
    public void afterSaleChgIsHandle(AfterSaleChgIsHandleDto asd) {
        update(new LambdaUpdateWrapper<AfterSale>().set(AfterSale::getIsHandle, asd.getIsHandle().getValue()).eq(AfterSale::getId, asd.getId()));
    }

    @Override
    public AfterSaleOrderDetilVo selectAfterSaleOrderDetil(Long id) {

        AfterSaleOrderDetilVo afterSaleOrderDetilVo = afterSaleMapper.selectAfterSaleOrderDetil(id);

        //售后最后一次操作记录
        AfterSaleOperationQuery afterSaleOperationQuery = new AfterSaleOperationQuery();
        afterSaleOperationQuery.setAfterSaleId(id);
        List<AfterSaleOperationVo> afterSaleOperationVoList = afterSaleOperationMapper.selectAfterSaleOperationList(afterSaleOperationQuery);
        if (afterSaleOperationVoList.size() > 0) {
            System.out.println(afterSaleOperationVoList);
            if (afterSaleOperationVoList.get(0) != null) {
                afterSaleOrderDetilVo.setOperationTime(afterSaleOperationVoList.get(0).getCreatedTime());
            }
            //商品图片list取一张   改为ordergoods表内商品图片
            /*Long goodsId = afterSaleOrderDetilVo.getGoodsId();
            GoodsDetailsVo goodsDetailsVo = goodsFeign.selectGoodsDetails(goodsId).getData();
            if(goodsDetailsVo!=null){
                String goodsImg = goodsDetailsVo.getGoodsImg().get(0);
                afterSaleOrderDetilVo.setImage(goodsImg);
            }*/
        }
        return afterSaleOrderDetilVo;
    }

    @Override
    public void afterSaleChgCustomerRemark(ChgCustomerRemarkDto chgCustomerRemarkDto) {
        afterSaleMapper.afterSaleChgCustomerRemark(chgCustomerRemarkDto);
    }

    @Override
    public IPage<AfterSaleProblemVo> selectAfterSaleProblemList(Page page, AfterSaleProblemQuery afterSaleProblemQuery) {
        SysAuth sysExt = AuthUtil.getSysExt();
        IPage<AfterSaleProblemVo> pageList = afterSaleMapper.selectAfterSaleProblemList(page, afterSaleProblemQuery);
        List<AfterSaleProblemVo> records = pageList.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (AfterSaleProblemVo orderVo : records) {
                orderVo.setContactPhone(sysExt.isSensitive() ? CommonUtil.coverMobile(orderVo.getContactPhone()) : orderVo.getContactPhone());
            }
        }
        return pageList;
    }

    @Override
    public IPage<AfterSaleListVo> getAfterSaleList(Page page, AfterSaleAppQuery afterSaleAppQuery) {
        return afterSaleMapper.getAfterSaleList(page, afterSaleAppQuery);
    }

    @Override
    public AfterSaleRefoundSuccessVo selectRefundSuccess(long id) {
        return afterSaleMapper.selectRefundSuccess(id);
    }

    @Override
    public AfterSaleExchangeGoodsSuccessVo selectExchangeGoodsSuccess(long id) {
        return afterSaleMapper.selectExchangeGoodsSuccess(id);
    }

    @Override
    public IPage<AppDepotAfterSaleVo> selectAppDepotAfterSaleList(Page page, AppDepotAfterSaleQuery appDepotAfterSaleQuery) {
        switch (appDepotAfterSaleQuery.getStatusStrs()) {
            case "1":
                appDepotAfterSaleQuery.setStatusStrs("25");
                break;
            case "2":
                appDepotAfterSaleQuery.setStatusStrs("0,1,2,16,19,22");
                break;
            case "3":
                appDepotAfterSaleQuery.setStatusStrs("3");//调整  只有客服驳回 才是真正驳回给用户  app仓驳回是给客服看的需并驳回给用户
                break;
        }
        IPage<AppDepotAfterSaleVo> iPage = afterSaleMapper.selectAppDepotAfterSaleList(page, appDepotAfterSaleQuery);
        List<AppDepotAfterSaleVo> records = iPage.getRecords();
        for (AppDepotAfterSaleVo record : records) {
            List<AfterSaleOperation> afterSaleOperations = afterSaleOperationMapper.selectList(new QueryWrapper<AfterSaleOperation>().eq("after_sale_id", record.getId()).orderByDesc("created_time"));
            if (afterSaleOperations.size() > 0) {
                //record.setAuditResult(AfterSaleAuditEnum.values()[afterSaleOperations.get(0).getAuditResult()]);
                record.setOperationTime(afterSaleOperations.get(0).getCreatedTime());
            }
        }

        return iPage;
    }

    @Override
    public AppDepotAfterSaleDetilVo selectAppDepotAfterSaleDetil(AppDepotAfterSaleDetilQuery appDepotAfterSaleDetilQuery) {
        SysAuth sysAuth = AuthUtil.getSysExt();
        AppDepotAfterSaleDetilVo appDepotAfterSaleDetilVo = afterSaleMapper.selectAppDepotAfterSaleDetil(appDepotAfterSaleDetilQuery);
        //图片采用ordergoods表内图片
        /*if(appDepotAfterSaleDetilVo!=null){
            Long goodsId = appDepotAfterSaleDetilVo.getGoodsId();
            GoodsDetailsVo goodsDetailsVo = goodsFeign.selectGoodsDetails(goodsId).getData();
            if(goodsDetailsVo!=null){
                String goodsImg = goodsDetailsVo.getGoodsImg().get(0);
                appDepotAfterSaleDetilVo.setImage(goodsImg);
            }
        }*/
        //查询审核人名称
        if (appDepotAfterSaleDetilVo != null && appDepotAfterSaleDetilVo.getAuditor() != null && appDepotAfterSaleDetilVo.getAuditDept() != null) {
            if (AuditDeptEnum.AGENT.getValue().equals(appDepotAfterSaleDetilVo.getAuditDept().getValue())) {
                AgentCustomerVo agentCustomerVo = agentServiceRpc.selectByIdAgentCustomer(appDepotAfterSaleDetilVo.getAuditor()).getData();
                if (agentCustomerVo != null) {
                    appDepotAfterSaleDetilVo.setAuditorName(agentCustomerVo.getAgentName());
                }
            }
            if (AuditDeptEnum.SERVICE_DEPT.getValue().equals(appDepotAfterSaleDetilVo.getAuditDept().getValue())) {
                UserInfoVo userInfoVo = sysUserRpcService.userInfo(appDepotAfterSaleDetilVo.getAuditor()).getData();
                if (userInfoVo != null) {
                    appDepotAfterSaleDetilVo.setAuditorName(userInfoVo.getUserName());
                }
            }
        }
        if (appDepotAfterSaleDetilVo != null) {
            appDepotAfterSaleDetilVo.setContactPhone(sysAuth.isSensitive() ? CommUtil.coverMobile(appDepotAfterSaleDetilVo.getContactPhone()) : appDepotAfterSaleDetilVo.getContactPhone());
        }
        return appDepotAfterSaleDetilVo;
    }

    /**
     * 二期项目进行了更改不在进行是否绑定了商品码绑定了
     *
     * @param scanCodeGoodsDetilQuery
     * @return
     */
    @Override
    public AppAuditDetilVo selectAppAuditDetil(ScanCodeGoodsDetilQuery scanCodeGoodsDetilQuery) {
        SysAuth sysAuth = AuthUtil.getSysExt();
        String commodityCode = commodityCodeOrProductSn(scanCodeGoodsDetilQuery.getQrCodeValue(), 0);
        if (StrUtil.isEmpty(commodityCode)) {
            return null;
        }
        String orderSn = orderBindingService.findOrderSnByCommodityCode(commodityCode);
        if (StrUtil.isEmpty(orderSn)) {
            return null;
        }
        scanCodeGoodsDetilQuery.setOrderSn(orderSn);

        AppAuditDetilVo appAuditDetilVo = afterSaleMapper.selectAppAuditDetil(scanCodeGoodsDetilQuery);
        if (appAuditDetilVo != null) {
            //商品图片  注释代码为商品图片   采用ordergoods表内商品图片
            /*Long goodsId = appAuditDetilVo.getGoodsId();
            GoodsDetailsVo goodsDetailsVo = goodsFeign.selectGoodsDetails(goodsId).getData();
            if(goodsDetailsVo!=null){
                String goodsImg = goodsDetailsVo.getGoodsImg().get(0);
                appAuditDetilVo.setImage(goodsImg);
            }*/

            Long afterSaleId = appAuditDetilVo.getAfterSaleId();
            //售后最后一次操作记录
            AfterSaleOperationQuery afterSaleOperationQuery = new AfterSaleOperationQuery();
            afterSaleOperationQuery.setAfterSaleId(afterSaleId);
            List<AfterSaleOperationVo> afterSaleOperationVoList = afterSaleOperationMapper.selectAfterSaleOperationList(afterSaleOperationQuery);
            if (afterSaleOperationVoList != null) {
                appAuditDetilVo.setOperationTime(afterSaleOperationVoList.get(0).getCreatedTime());
            }
            appAuditDetilVo.setContactPhone(sysAuth.isSensitive() ? CommUtil.coverMobile(appAuditDetilVo.getContactPhone()) : appAuditDetilVo.getContactPhone());
        }
        return appAuditDetilVo;
    }

    private String commodityCodeOrProductSn(String qrCodeValue, int i) {//i 只能是 0 (commodityCode)或 1 (ProductSn)
        if (StrUtil.isNotEmpty(qrCodeValue)) {
            int index = qrCodeValue.lastIndexOf("/");
            if (qrCodeValue.length() <= index) {
                return "";
            }
            String qrCode = qrCodeValue.substring(index + 1);
            String[] codeArray = qrCode.split("_");
            return codeArray.length > i ? codeArray[i] : "";
        }
        return "";
    }

    //新增售后记录
    private Long insertAfterSale(ReceiveOrderDto receiveOrderDto, Long uid) {
        Long afterSaleId = null;
        ScanCodeGoodsDetilQuery scgdq = new ScanCodeGoodsDetilQuery();
        scgdq.setGoodsSn(receiveOrderDto.getGoodsSn());
        scgdq.setOrderSn(receiveOrderDto.getOrderSn());
        ScanCodeGoodsDetilVo scgdv = orderMapper.selectScanCodeGoodsDetil(scgdq);
        if (scgdv != null) {
            AfterSaleDto afterSaleDto = new AfterSaleDto();
            afterSaleDto.setAfterSaleType(receiveOrderDto.getAfterSaleType());
            afterSaleDto.setApplyReason(receiveOrderDto.getApplyReason());
            afterSaleDto.setReasonDesp(receiveOrderDto.getAfterSaleRemark());
            afterSaleDto.setReceiveRemark(receiveOrderDto.getReceivedRemark());
            afterSaleDto.setQuantity(1);
            afterSaleDto.setOrderId(scgdv.getId());
            afterSaleDto.setProductId(scgdv.getProductId());
            save(afterSaleDto, uid);
            //自增Id保存后去查询记录Id
            AfterSale afterSale = getOne(new LambdaQueryWrapper<AfterSale>().eq(AfterSale::getOrderId, scgdv.getId()).eq(AfterSale::getProductId, scgdv.getProductId()));
            if (afterSale != null) {
                afterSaleId = afterSale.getId();
                afterSale.setReceiveTag(1);
                updateById(afterSale);
            }
            if (scgdv.getId() != null) {
                //新增更新是否换货状态
                if (receiveOrderDto.getAfterSaleType().getValue().equals(AfterSalesTypeEnum.EXCHANE_GOODS.getValue())) {
                    //将主订单状态修改为售后中状态  并且将是否换货标记改为换货标识
                    orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId, scgdv.getId())
                            .set(Order::getOrderStatus, OrderStateEnum.AFTER_SALE.getValue())
                            .set(Order::getAfterSaleTag, 1));
                } else {
                    //将主订单状态修改为售后中状态
                    orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId, scgdv.getId()).set(Order::getOrderStatus, OrderStateEnum.AFTER_SALE.getValue()));
                }
            }
        }
        return afterSaleId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receive(ReceiveOrderDto receiveOrderDto, Long uid) {
        //校验是否有售后记录
        if (receiveOrderDto.getAfterSaleId() == null) {//新增售后记录
            receiveOrderDto.setAfterSaleId(insertAfterSale(receiveOrderDto, uid));
        } else {
            //校验是否是待审核状态
            AfterSale afterSale = getById(receiveOrderDto.getAfterSaleId());
            if (ObjectUtil.isEmpty(afterSale) || !AfterSaleAuditEnum.WAIT_AUIT.getValue().equals(afterSale.getStatus())) {
                throw new BusinessException("非售后初始状态不可操作");
            }
        }
        Assert.notNull(receiveOrderDto.getAfterSaleId(), "售后参数异常");
        Assert.notNull(receiveOrderDto.getAuditOperation(), "操作类型参数为空");
        SysUserEditVo sysUserEditVo = null;
        Result<SysUserEditVo> result = sysConfigService.getUserById(uid);
        if (result.isSuccess()) {
            sysUserEditVo = result.getData();
        }
        String userName = "";
        if (sysUserEditVo != null) {
            userName = sysUserEditVo.getRealName();
        }
        //接收时间
        Date receviceTime = new Date();
        receiveOrderDto.setReveiveTime(receviceTime);
        receiveOrderDto.setReceivedBy(userName);
        //重新定义app操作员状态 通过审核都是等待客服审核
        /*if(receiveOrderDto.getAuditOperation() == 1){
            receiveOrderDto.setAfterSaleStatus(AfterSaleAuditEnum.WAIT_AUIT);
        }else if(receiveOrderDto.getAuditOperation() == 2){// 复审也是app在操作不改变主状态
            receiveOrderDto.setAfterSaleStatus(AfterSaleAuditEnum.PASS_AUIT);
        }*/
        receiveOrderDto.setAfterSaleStatus(AfterSaleAuditEnum.WAIT_AUIT);
        //receiveOrderDto.setAfterSaleResult(AfterSaleResultEnum.IN_DEFE);
        afterSaleMapper.receive(receiveOrderDto);

        AfterSale afterSale = getById(receiveOrderDto.getAfterSaleId());
        //更新订单标签状态
        if (ObjectUtil.isNotEmpty(afterSale)) {
            Order order=orderService.getById(afterSale.getOrderId());
            if(afterSale.getAfterSaleType().equals(AfterSalesTypeEnum.RETURN_GOODS.getValue())){
                orderService.updateTag(afterSale.getOrderId(), OrderSysTagEnum.THZ_TAG_501.getValue(), OrderAppTagEnum.THZ_TAG_501.getValue());
                order.setAfterSaleTag(0);

            }else{
                orderService.updateTag(afterSale.getOrderId(), OrderSysTagEnum.THZ_HHG_507.getValue(), OrderAppTagEnum.THZ_HHG_507.getValue());
                order.setAfterSaleTag(1);
            }
                orderService.updateById(order);
        }
        //售后操作记录
        AfterSaleOperation afterSaleOperation = new AfterSaleOperation();
        //接收员id
        afterSaleOperation.setOperatorId(uid);
        //接收员姓名
        afterSaleOperation.setOperator(userName);
        //售后订单
        afterSaleOperation.setAfterSaleId(receiveOrderDto.getAfterSaleId());
        //角色为接收员
        afterSaleOperation.setOperatorType(AfterSaleOperatorTypeEnum.TYPE1.getValue());
        if (receiveOrderDto.getAuditOperation() == 1) {
            //接收通过
            afterSaleOperation.setAuditResult(AfterSaleAuditEnum.WAIT_AUIT.getValue());
            //审核备注
            afterSaleOperation.setAuditRemark("接收通过");
            //操作备注
            afterSaleOperation.setOperatorRemark("接收通过");
        } else if (receiveOrderDto.getAuditOperation() == 2) {
            //审核通过 -- 重新定义状态值
            //afterSaleOperation.setAuditResult(AfterSaleAuditEnum.PASS_AUIT.getValue());
            afterSaleOperation.setAuditResult(AfterSaleAuditEnum.WAIT_AUIT.getValue());
            //审核备注
            afterSaleOperation.setAuditRemark("审核通过");
            //操作备注
            afterSaleOperation.setOperatorRemark("审核通过");
        }
        afterSaleOperation.setCreatedTime(receviceTime);
        afterSaleOperationMapper.insert(afterSaleOperation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refuse(ReceiveOrderDto receiveOrderDto, Long uid) {
        //校验是否有售后记录
        if (receiveOrderDto.getAfterSaleId() == null) {//新增售后记录
            receiveOrderDto.setAfterSaleId(insertAfterSale(receiveOrderDto, uid));
        }
        Assert.notNull(receiveOrderDto.getAfterSaleId(), "售后参数异常");
        Assert.notNull(receiveOrderDto.getAuditOperation(), "操作类型参数为空");
        SysUserEditVo sysUserEditVo = null;
        Result<SysUserEditVo> result = sysConfigService.getUserById(uid);
        if (result.isSuccess()) {
            sysUserEditVo = result.getData();
        }
        String userName = "";
        if (sysUserEditVo != null) {
            userName = sysUserEditVo.getRealName();
        }
        //接收时间
        Date receviceTime = new Date();
        receiveOrderDto.setReveiveTime(receviceTime);
        receiveOrderDto.setReceivedBy(userName);
        /*if(receiveOrderDto.getAuditOperation() == 1){
            receiveOrderDto.setAfterSaleStatus(AfterSaleAuditEnum.APP_REFUSE_AUIT);
        }else if(receiveOrderDto.getAuditOperation() == 2){
            receiveOrderDto.setAfterSaleStatus(AfterSaleAuditEnum.REFUSE_AUIT);
        }*/
        receiveOrderDto.setAfterSaleStatus(AfterSaleAuditEnum.APP_REFUSE_AUIT);
        receiveOrderDto.setAfterSaleResult(AfterSaleResultEnum.REJECT);
        afterSaleMapper.refuse(receiveOrderDto);
        //售后被拒绝订单售后中状态变更为已完成
        AfterSale afterSale = getById(receiveOrderDto.getAfterSaleId());
        if (afterSale != null && afterSale.getOrderId() != null) {
            orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId, afterSale.getOrderId()).set(Order::getOrderStatus, OrderStateEnum.FINISHED.getValue()));
        }
        //更新订单标签状态
        if (ObjectUtil.isNotEmpty(afterSale)) {
            orderService.updateTag(afterSale.getOrderId(), OrderSysTagEnum.YJJC_TAG_503.getValue(), OrderAppTagEnum.YJJC_TAG_503.getValue());
        }
        //售后操作记录
        AfterSaleOperation afterSaleOperation = new AfterSaleOperation();
        //接收员id
        afterSaleOperation.setOperatorId(uid);
        //接收员姓名
        afterSaleOperation.setOperator(userName);
        //售后订单
        afterSaleOperation.setAfterSaleId(receiveOrderDto.getAfterSaleId());
        //角色为接收员
        afterSaleOperation.setOperatorType(AfterSaleOperatorTypeEnum.TYPE1.getValue());
        if (receiveOrderDto.getAuditOperation() == 1) {
            //接收失败
            afterSaleOperation.setAuditResult(AfterSaleAuditEnum.APP_REFUSE_AUIT.getValue());
            //接收失败备注
            afterSaleOperation.setAuditRemark("接收失败");
            //操作备注
            afterSaleOperation.setOperatorRemark("接收失败");
        } else if (receiveOrderDto.getAuditOperation() == 2) {
            //审核拒绝 ----  重新定义状态值
            /*afterSaleOperation.setAuditResult(AfterSaleAuditEnum.REFUSE_AUIT.getValue());*/
            afterSaleOperation.setAuditResult(AfterSaleAuditEnum.APP_REFUSE_AUIT.getValue());
            //审核备注
            afterSaleOperation.setAuditRemark("审核失败");
            //操作备注
            afterSaleOperation.setOperatorRemark("审核失败");
        }
        afterSaleOperation.setCreatedTime(receviceTime);
        afterSaleOperationMapper.insert(afterSaleOperation);
    }

    @Override
    public void updateItemStausByOrderId(Long orderId, ProductStatusEnum productStatus) {
        UpdateWrapper<AfterSale> uw = new UpdateWrapper<>();
        uw.eq("order_id", orderId);
        update(new AfterSale().setItemStatus(productStatus.getValue()), uw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAfterSaleStatusVal(Long id, Integer type, Integer afterSaleAudit, Integer afterSaleResult, Integer productStatus, Long operatorId, String operatorName) {
        if (id != null) {
            String result = "";
            if (type == 1) {// 入APP仓
                result = "入APP仓";
                afterSaleResult = AfterSaleResultEnum.INTO_APP.getValue();
            } else if (type == 2) {//入次品库
                result = "入次品库";
                afterSaleResult = AfterSaleResultEnum.IN_DEFE.getValue();
            }
            AfterSale afterSale = getById(id);
            if (ObjectUtil.isNotEmpty(afterSale)) {
                //入app仓时解绑商品订单绑定
                orderBindingService.cancelBindingByOrderIdOrCommodityCode("", afterSale.getOrderId());
                //TODO，入APP仓库，仓库新入库一个商品，同时新建一个库位、编号的表和APP仓库对应起来。
            }
            //若为换货则将主订单重置为待发货订单 并且将生成调拨单状态至为未生成 逻辑暂时如此
            // 客户新逻辑 此逻辑废弃移走单独处理放在换货确认处理方法内 2022-04-12
            //  客户逻辑在调整，现在允许退货的商品继续入库操作。
            if (ObjectUtil.isNotEmpty(afterSale) && afterSale.getAfterSaleType() != null
                    && AfterSalesTypeEnum.EXCHANE_GOODS.getValue().equals(afterSale.getAfterSaleType().intValue()) && afterSale.getOrderId() != null) {
              /*  //查询订单信息获取原始快递单号
                Order order = orderService.getById(afterSale.getOrderId());
                orderService.update(new LambdaUpdateWrapper<Order>().set(Order::getOrderStatus, OrderStateEnum.AUDIT_SUCCESS.getValue())
                        .set(Order::getIsCreatedBill, IsCreatedBillEnum.NO.getValue())
                        .set(Order::getBeforExpressSn,order.getExpressSn())
                        .set(Order::getExpressSn,"")
                        .eq(Order::getId, afterSale.getOrderId()));
                afterSaleAudit = AfterSaleAuditEnum.WAIT_SHIP.getValue();*/
            } else {//若为退货则售后状态已完成
                afterSaleAudit = AfterSaleAuditEnum.FINISHED.getValue();


                try{
                    //回滚代理商返利
                    Result resultProfit = agentProfitFeign.unProfit(afterSale.getOrderId());
                   /* if (!resultProfit.isSuccess()) {
                        System.out.println("调用回滚返利服务失败");
                    }*/
                }catch (Exception e){

                }


                //订单退货操作日志
               orderLogService.addOrderLog(afterSale.getOrderId(), OrderLogTypeEnum.REFUND.getValue(), operatorId, operatorName);
            }

            LambdaUpdateWrapper<AfterSale> luw = new LambdaUpdateWrapper<>();
            luw.eq(AfterSale::getId, id);
            if (afterSaleAudit != null) {
                luw.set(AfterSale::getStatus, afterSaleAudit);
            }
            if (afterSaleResult != null) {
                luw.set(AfterSale::getAfterSaleResult, afterSaleResult);
            }
            if (productStatus != null) {
                luw.set(AfterSale::getItemStatus, productStatus);
            }
            luw.set(AfterSale::getCheckTime, new Date());
            update(luw);
            Order order = orderMapper.selectById(afterSale.getOrderId());
            if (ObjectUtil.isNotNull(order) ) {
                //变更订单标签状态  这种情况不在更改标签状态了。
                if (ObjectUtil.isNotEmpty(afterSale)&& afterSale.getAfterSaleType().equals(AfterSalesTypeEnum.RETURN_GOODS.getValue())) {
                    orderService.updateTag(afterSale.getOrderId(), OrderSysTagEnum.YTHC_TAG_505.getValue(), OrderAppTagEnum.YTHC_TAG_505.getValue());
                }
                Order order1=new Order();
                order1.setId(order.getId());
                order1.setUpdatedTime( new Date());
                orderService.updateById(order1);
            }
            //售后操作记录
            AfterSaleOperation afterSaleOperation = new AfterSaleOperation();
            //操作员id
            afterSaleOperation.setOperatorId(operatorId);
            //操作员姓名
            afterSaleOperation.setOperator(operatorName);
            //售后订单
            afterSaleOperation.setAfterSaleId(id);
            //角色为接收员
            afterSaleOperation.setOperatorType(AfterSaleOperatorTypeEnum.TYPE2.getValue());
            afterSaleOperation.setAuditResult(afterSaleAudit);
            //审核备注
            afterSaleOperation.setAuditRemark(result);
            //操作备注
            afterSaleOperation.setOperatorRemark(result);
            afterSaleOperation.setCreatedTime(DateUtil.date());
            afterSaleOperationMapper.insert(afterSaleOperation);
        }
    }

    @Override
    public void updateDepotInfo(Long id, String depotSn, String depotLocation, String depotOrder) {
        if (id != null) {
            AfterSale afterSale = new AfterSale();
            afterSale.setId(id);
            afterSale.setDepotSn(depotSn);
            afterSale.setDepotLocation(depotLocation);
            afterSale.setDepotOrder(depotOrder);
            updateById(afterSale);
        }
    }

    @Override
    public void confirmHandleAfterOrder(Long id, Long orderId) {
        AfterSale afterSale = new AfterSale();
        afterSale.setId(id);
        afterSale.setStatus(AfterSaleAuditEnum.WAIT_SHIP.getValue());
        afterSale.setConfirmHandle(AfterSaleIsHandleEnum.YES.getValue());
        updateById(afterSale);


        AfterSale sale = getById(id);
        //更新订单标签状态
        if (sale.getAfterSaleType().equals(AfterSalesTypeEnum.RETURN_GOODS.getValue())) {
            //二期项目对于退货的流程不进行调整，不更新状态。
            //orderService.updateTag(orderId, OrderSysTagEnum.DFH_TAG_108.getValue(), OrderAppTagEnum.THZ_TAG_501.getValue());
        } else {
            orderService.updateTag(orderId, OrderSysTagEnum.DFH_TAG_108.getValue(), OrderAppTagEnum.THZ_HHG_507.getValue());
            //换货执行商品码解绑操作
            orderBindingService.cancelBindingByOrderIdOrCommodityCode("", sale.getOrderId());
            goodsService.update(new LambdaUpdateWrapper<OrderGoods>().eq(OrderGoods::getOrderId, sale.getOrderId()).set(OrderGoods::getCommodityCode, null));
            // 二期项目换货流程调整，在后台换过颜色和尺码之后就要跳转到待发货页面进行。
            orderService.update(new LambdaUpdateWrapper<Order>().eq(Order::getId, orderId)
                    .set(Order::getOrderStatus, OrderStateEnum.WAIT_SHIP.getValue())
                    .set(Order::getItemStatus, ProductStatusEnum.STATUS8.getValue())
                    .set(Order::getFrontOrderStatus, OrderFrontStateEnum.WAIT_SHIP.getValue())
                    .set(Order::getStockId, null)
                    .set(Order::getStockSn, null)
                    .set(Order::getDepotName, null)
                    .set(Order::getDepotCode, null)
                    .set(Order::getDepotId, null));
        }
      /*  orderService.update(new LambdaUpdateWrapper<Order>().set(Order::getOrderStatus, OrderStateEnum.AUDIT_SUCCESS.getValue())
                .set(Order::getIsCreatedBill, IsCreatedBillEnum.NO.getValue())
                .set(Order::getBeforExpressSn, order.getExpressSn())
                .set(Order::getExpressSn, "")
                .set(Order::getAfterSaleTag, 1)
                .eq(Order::getId, orderId));*//**/
    }

    /**
     * 根据订单ID返回售后序号
     *
     * @param orderId
     * @return
     */
    @Override
    public Long selfIncreasing(Long orderId) {
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        Order order = orderService.getById(orderId);
        Long result = 0L;
        for (OrderTypeEnum orderTypeEnum : OrderTypeEnum.values()) {
            if (order.getOrderType().intValue() == orderTypeEnum.getValue().intValue()) {
                String key = orderTypeEnum.name() + date+order.getCustomerId();
                String tmp = stringRedisTemplate.opsForValue().get(key + order.getId());
                if (null == tmp) {
                    result = stringRedisTemplate.opsForValue().increment(key, 1);
                    stringRedisTemplate.opsForValue().set(key + order.getId(), result.toString());
                } else {
                    result = Long.valueOf(tmp);
                }

            }
        }
        return result;
    }

    /**
     * 检查仓库与客服人员的绑定关系
     *
     * @param sysAuth 当前登录人员
     * @param orderId 订单信息
     * @return
     */
    @Override
    public String chekBinding(SysAuth sysAuth, Long orderId) {
        Order order = orderService.getById(orderId);
        if (null == order) {
            return "订单编号错误，不存在该订单！";
        }
        Result result = sysUserRpcService.checkBind(order.getCustomerId(), sysAuth.getUid());
        if (result != null && result.getCode() == ResultCodeEnum.ERROR.getCode()) {
            return result.getMsg();
        }
        return null;
    }

    /**
     * 更改退换货状态，返回null 代表成功，返回1代表状态一致，不进行修改，返回2代表状态不对，不允许切换退换货
     *
     * @param afterSaleChgProblemDto
     * @return
     */
    @Override
    public String changeStatus(AfterSaleChgTypeDto afterSaleChgProblemDto) {
        AfterSale afterSale = afterSaleMapper.selectById(afterSaleChgProblemDto.getId());
        if (afterSale.getAfterSaleType().intValue() == afterSaleChgProblemDto.getAfterSaleType().getValue().intValue()) {
            return "1";
        }
        List<Integer> checkStatusList = Lists.newArrayList();
        checkStatusList.add(AfterSaleAuditEnum.WAIT_AUIT.getValue());
        checkStatusList.add(AfterSaleAuditEnum.PASS_AUIT.getValue());
        checkStatusList.add(AfterSaleAuditEnum.APP_REFUSE_AUIT.getValue());
        checkStatusList.add(AfterSaleAuditEnum.REFUSE_AUIT.getValue());
        if (checkStatusList.contains(afterSale.getStatus())) {
            afterSale.setAfterSaleType(afterSaleChgProblemDto.getAfterSaleType().getValue());
            Order order = orderMapper.selectById(afterSale.getOrderId());
            if (ObjectUtil.isNotNull(order)) {
                order.setAppTag(OrderAppTagEnum.THZ_TAG_501.getValue().equals(order.getAppTag()) ? OrderAppTagEnum.THZ_HHG_507.getValue() : OrderAppTagEnum.THZ_TAG_501.getValue());
                order.setSysTag(OrderSysTagEnum.THZ_TAG_501.getValue().equals(order.getSysTag()) ? OrderSysTagEnum.THZ_HHG_507.getValue() : OrderSysTagEnum.THZ_TAG_501.getValue());
                order.setAfterSaleTag(OrderAppTagEnum.THZ_TAG_501.getValue().equals(order.getAppTag())?1:0);
                orderMapper.updateById(order);
            }

            afterSaleMapper.updateById(afterSale);
        } else {
            return "2";
        }
        return null;
    }

    @Override
    public boolean checkOrder(AfterSaleDto afterSaleDto) {
        Order orderItemVo = orderMapper.selectById(afterSaleDto.getOrderId());
        if (orderItemVo.getAfterSaleTag().intValue() == 2 && afterSaleDto.getReasonDesp().equals("瑕疵")) {
            if (afterSaleDto.getImgs().length > 0 && afterSaleDto.getImgs().length < 5) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    @Override
    public AfterSale selectByOrderId(long orderId) {
        LambdaQueryWrapper<AfterSale> wrapper = new LambdaQueryWrapper<AfterSale>();
        wrapper.eq(AfterSale::getOrderId, orderId);
        return getOne(wrapper);
    }

    @Override
    public IPage<AfterSaleVo> loadAfterSaleList(Page page, CustomerOrderQuery query) {
        return baseMapper.loadAfterSaleList(page, query);
    }

    @Override
    public StaticVo loadAfterSaleTotal(CustomerOrderQuery query) {

        return baseMapper.loadAfterSaleTotal(query);
    }


}
